package com.example.smartpark.controller;

import com.example.smartpark.common.Result;
import com.example.smartpark.dto.ChangePasswordDTO;
import com.example.smartpark.dto.UserProfileUpdateDTO;
import com.example.smartpark.dto.VehicleAddDTO;
import com.example.smartpark.dto.VehicleUpdateDTO;
import com.example.smartpark.service.UserService;
import com.example.smartpark.utils.JwtUtils;
import com.example.smartpark.vo.UserVO;
import com.example.smartpark.vo.VehicleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 * 处理用户信息相关请求
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取当前用户信息
     *
     * @param token JWT令牌
     * @return 用户信息
     */
    @GetMapping("/info")
    public Result<UserVO> getUserInfo(@RequestHeader("Authorization") String token) {
        // 从token中提取用户ID
        Integer userId = JwtUtils.getUserIdFromToken(token.replace("Bearer ", ""));
        if (userId == null) {
            return Result.error(401, "无效的令牌");
        }

        log.info("获取用户信息: userId={}", userId);
        UserVO userVO = userService.getUserInfo(userId);
        return Result.success(userVO);
    }

    /**
     * 注销登录
     *
     * @return 注销结果
     */
    @PostMapping("/logout")
    public Result<Void> logout() {
        // JWT无状态，客户端只需要删除token即可
        // 这里只是提供一个接口，实际不做处理
        return Result.success(null, "注销成功");
    }

    /**
     * 获取用户个人资料
     *
     * @param token JWT令牌
     * @return 用户个人资料
     */
    @GetMapping("/profile")
    public Result<UserVO> getUserProfile(@RequestHeader("Authorization") String token) {
        // 从token中提取用户ID
        Integer userId = JwtUtils.getUserIdFromToken(token.replace("Bearer ", ""));
        if (userId == null) {
            return Result.error(401, "无效的令牌");
        }

        log.info("获取用户个人资料: userId={}", userId);
        UserVO userVO = userService.getUserProfile(userId);
        return Result.success(userVO);
    }

    /**
     * 更新用户个人资料
     *
     * @param token JWT令牌
     * @param profileUpdateDTO 用户资料更新DTO
     * @return 更新后的用户个人资料
     */
    @PutMapping("/profile")
    public Result<UserVO> updateUserProfile(
            @RequestHeader("Authorization") String token,
            @RequestBody @Valid UserProfileUpdateDTO profileUpdateDTO) {
        // 从token中提取用户ID
        Integer userId = JwtUtils.getUserIdFromToken(token.replace("Bearer ", ""));
        if (userId == null) {
            return Result.error(401, "无效的令牌");
        }

        log.info("更新用户个人资料: userId={}, 更新数据={}", userId, profileUpdateDTO);
        UserVO updatedUserVO = userService.updateUserProfile(userId, profileUpdateDTO);
        return Result.success(updatedUserVO, "更新个人资料成功");
    }

    /**
     * 修改用户密码
     *
     * @param token JWT令牌
     * @param changePasswordDTO 修改密码DTO
     * @return 修改结果
     */
    @PostMapping("/change-password")
    public Result<Void> changePassword(
            @RequestHeader("Authorization") String token,
            @RequestBody @Valid ChangePasswordDTO changePasswordDTO) {
        // 从token中提取用户ID
        Integer userId = JwtUtils.getUserIdFromToken(token.replace("Bearer ", ""));
        if (userId == null) {
            return Result.error(401, "无效的令牌");
        }

        log.info("修改用户密码: userId={}", userId);
        boolean success = userService.changePassword(userId, changePasswordDTO);

        if (success) {
            return Result.success(null, "密码修改成功");
        } else {
            return Result.error(500, "密码修改失败");
        }
    }

    /**
     * 获取用户车辆列表
     *
     * @param token JWT令牌
     * @return 车辆列表
     */
    @GetMapping("/vehicles")
    public Result<List<VehicleVO>> getUserVehicles(@RequestHeader("Authorization") String token) {
        // 从token中提取用户ID
        Integer userId = JwtUtils.getUserIdFromToken(token.replace("Bearer ", ""));
        if (userId == null) {
            return Result.error(401, "无效的令牌");
        }

        log.info("获取用户车辆列表: userId={}", userId);
        List<VehicleVO> vehicles = userService.getUserVehicles(userId);
        return Result.success(vehicles);
    }

    /**
     * 添加车辆
     *
     * @param token JWT令牌
     * @param vehicleAddDTO 添加车辆DTO
     * @return 添加的车辆信息
     */
    @PostMapping("/vehicles")
    public Result<VehicleVO> addVehicle(
            @RequestHeader("Authorization") String token,
            @RequestBody @Valid VehicleAddDTO vehicleAddDTO) {
        // 从token中提取用户ID
        Integer userId = JwtUtils.getUserIdFromToken(token.replace("Bearer ", ""));
        if (userId == null) {
            return Result.error(401, "无效的令牌");
        }

        log.info("添加车辆: userId={}, vehicleAddDTO={}", userId, vehicleAddDTO);
        VehicleVO vehicleVO = userService.addVehicle(userId, vehicleAddDTO);
        return Result.success(vehicleVO, "添加车辆成功");
    }

    /**
     * 更新车辆信息
     *
     * @param token JWT令牌
     * @param id 车辆ID
     * @param vehicleUpdateDTO 更新车辆DTO
     * @return 更新后的车辆信息
     */
    @PutMapping("/vehicles/{id}")
    public Result<VehicleVO> updateVehicle(
            @RequestHeader("Authorization") String token,
            @PathVariable("id") Integer id,
            @RequestBody @Valid VehicleUpdateDTO vehicleUpdateDTO) {
        // 从token中提取用户ID
        Integer userId = JwtUtils.getUserIdFromToken(token.replace("Bearer ", ""));
        if (userId == null) {
            return Result.error(401, "无效的令牌");
        }

        log.info("更新车辆: userId={}, vehicleId={}, vehicleUpdateDTO={}", userId, id, vehicleUpdateDTO);
        VehicleVO vehicleVO = userService.updateVehicle(userId, id, vehicleUpdateDTO);
        return Result.success(vehicleVO, "更新车辆信息成功");
    }

    /**
     * 删除车辆
     *
     * @param token JWT令牌
     * @param id 车辆ID
     * @return 删除结果
     */
    @DeleteMapping("/vehicles/{id}")
    public Result<Void> deleteVehicle(
            @RequestHeader("Authorization") String token,
            @PathVariable("id") Integer id) {
        // 从token中提取用户ID
        Integer userId = JwtUtils.getUserIdFromToken(token.replace("Bearer ", ""));
        if (userId == null) {
            return Result.error(401, "无效的令牌");
        }

        log.info("删除车辆: userId={}, vehicleId={}", userId, id);
        boolean success = userService.deleteVehicle(userId, id);

        if (success) {
            return Result.success(null, "删除车辆成功");
        } else {
            return Result.error(500, "删除车辆失败");
        }
    }

    /**
     * 获取用户余额
     */
    @GetMapping("/balance")
    public Result<Map<String, Object>> getUserBalance(@RequestHeader("Authorization") String token) {
        log.info("获取用户余额");
        Integer userId = JwtUtils.getUserIdFromToken(token.replace("Bearer ", ""));
        BigDecimal balance = userService.getUserBalance(userId);
        Map<String, Object> data = new HashMap<>();
        data.put("balance", balance);
        return Result.success(data);
    }

    /**
     * 用户余额充值
     */
    @PostMapping("/balance/recharge")
    public Result<Map<String, Object>> rechargeBalance(
            @RequestBody Map<String, Object> params,
            @RequestHeader("Authorization") String token) {
        log.info("用户余额充值: params={}", params);

        Integer userId = JwtUtils.getUserIdFromToken(token.replace("Bearer ", ""));
        BigDecimal amount = new BigDecimal(params.get("amount").toString());

        BigDecimal newBalance = userService.rechargeBalance(userId, amount);

        Map<String, Object> data = new HashMap<>();
        data.put("balance", newBalance);
        return Result.success(data);
    }
}
